﻿using System;
using System.IO;
using System.Text;

using Vibstudio.X4NET.IO.INI.Model;

namespace Vibstudio.X4NET.IO.INI
{
    #region Namespaces

    

    #endregion

    public class FileIniDataParser : StreamIniDataParser
    {
        public IniData ReadFile(string filePath)
        {
            return ReadFile(filePath, Encoding.Default);
        }

        public IniData ReadFile(string filePath, Encoding fileEncoding)
        {
            if (filePath == string.Empty) throw new ArgumentException("Bad filename.");

            try
            {
                using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read))
                {
                    using (StreamReader sr = new StreamReader(fs, fileEncoding))
                    {
                        return ReadData(sr);
                    }
                }
            }
            catch (IOException ex)
            {
                throw new ParsingException(String.Format("Could not parse file {0}", filePath), ex);
            }
        }
                             
        public void WriteFile(string filePath, IniData parsedData, Encoding fileEncoding = null)
        {
    		if (fileEncoding == null)
				fileEncoding = Encoding.ASCII;

            if (string.IsNullOrEmpty(filePath))
                throw new ArgumentException("Bad filename.");

            if (parsedData == null)
                throw new ArgumentNullException("parsedData");

            using (FileStream fs = File.Open(filePath, FileMode.Create, FileAccess.Write))
            {
                using (StreamWriter sr = new StreamWriter(fs, fileEncoding))
                {
                    WriteData(sr, parsedData);
                }
            }
        }
    }
}
